package com.subfg.common.config;

import com.alibaba.fastjson.JSONObject;
import com.subfg.common.entity.excpetion.BusinessExceptionModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Configuration
@EnableScheduling
public class NacosServerConfig {
    private Logger log = LoggerFactory.getLogger(NacosServerConfig.class);

    public static Map<String, List<ServiceInstance>> nacosServerMap = new ConcurrentHashMap<>();

    @Autowired
    private DiscoveryClient discoveryClient;

    @Bean
    public void initNacosServerMap() {
        updateNacosServerMap();
    }


    public synchronized void updateNacosServerMap() {
        if (!nacosServerMap.isEmpty()) {
            nacosServerMap.clear();
        }
        List<String> getServicesList = discoveryClient.getServices();
        for (String serviceName : getServicesList) {
                List<ServiceInstance> listService = discoveryClient.getInstances(serviceName);
                nacosServerMap.put(serviceName, listService);
        }
        log.info("修改nacos服务成功, 目前在线服务如下:" + JSONObject.toJSONString(nacosServerMap));
    }

    @Scheduled(cron = "0 0/1 * * * ?")
    public void taskUpdateNacosServerMap() {
        updateNacosServerMap();
    }

    public ServiceInstance choose(String server) throws BusinessExceptionModel {
        Random random = new Random();
        List<ServiceInstance> serviceInstanceList = nacosServerMap.get(server);
        if (serviceInstanceList.isEmpty()) {
            throw new BusinessExceptionModel();
        }
        return serviceInstanceList.get(random.nextInt(serviceInstanceList.size()));
    }
}
